package com.apes.fn.scm.retailOrder.service;

import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.repository.RetailOrderRepository;
import com.apes.fn.scm.retailOrder.service.account.RetailAccountData;
import com.apes.fn.scm.retailOrder.service.account.RetailAccountService;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 零售单生成三方凭证逻辑
 * 定损业务
 * <p>
 * 确保 insuranceRule 表中的数据准确性
 * </p>
 * @author wuq
 * @create 2020-04-05 17:20
 */
@Service
public class RetailOrderFnVoucherService extends DomainService {

    @Autowired
    private RetailAccountService retailAccountService;

    public void createByEsb(SimpleRequest request) {
        String id = request.get("id");
        RetailOrder retailOrder = SpringManager.getBean(RetailOrderRepository.class).findOne(id);
        process(retailOrder);
    }

    private void sendDingMessage(String msg) {
        EventUtil.sendSynEvent(this, "event:dingding.message.publish", MapUtil.mapper(
                "userList", "05312315653782,01487,01120910513236528216",
                "content", "【赋能定损场景流报错】" + "\n" + msg
        ));
    }

    public void create(SimpleRequest simpleRequest) {
        RetailOrder retailOrder = simpleRequest.getO(RetailOrder.class);
        try {
            process(retailOrder);
        } catch (Exception e) {
            sendDingMessage(Tools.getThrowable(e).getMessage());
            throw new RuntimeException(e);
        }
    }

    public void process(RetailOrder retailOrder) {
        retailAccountService.process("insurance", new RetailAccountData(retailOrder));
    }

}
